package com.hcms.common.utils.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

// 树 json 工具类
public class TreeUtil {

    // 获取树
    public <T extends TreeNode> List<T> getTree(List<T> allList) {
        List<T> list = getRootNode(allList);
        list.forEach(item -> {
            item = getChildrenNode(item, allList);
        });
        return list;
    }

    // 获取根节点
    private <T extends TreeNode> List<T> getRootNode(List<T> allList) {
        List<T> rootNode = new ArrayList<>();
        allList.forEach(item -> {
            if (item.getParentId() == 0) {
                rootNode.add(item);
            }
        });
        return rootNode;
    }

    // 构建子树
    private <T extends TreeNode> T getChildrenNode(T rootNode, List<T> allList) {
        List<T> childernList = new ArrayList<>();
        allList.forEach(item -> {
            if (Objects.equals(item.getParentId(), rootNode.getId())) {
                T t = getChildrenNode(item, allList);
                childernList.add(t);
            }
        });
        rootNode.setChildren((List<TreeNode>) childernList);
        return rootNode;
    }
}
